<template>
  <div class="tag-list-container">
    <div class="tag-list-header">
      <div class="header-left">
        <h2>标签管理</h2>
        <p class="header-subtitle">共 {{ tags.length }} 个标签</p>
      </div>
      <a-button type="primary" @click="showAddModal" class="add-tag-button">
        <template #icon><PlusOutlined /></template>
        新增标签
      </a-button>
    </div>

    <a-card class="tag-card">
      <a-table
        v-if="!loading && tags.length !== 0"
        :columns="columns"
        :data-source="tags"
        row-key="id"
        :pagination="false"
        class="tag-table"
        :scroll="{ x: 'max-content' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <a-tag :color="getTagColor(record.name)" class="tag-item">
              {{ record.name }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'count'">
            <a-tag color="blue" class="count-tag">
              {{ record.count || 0 }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'showInNav'">
            <a-tag :color="record.showInNav ? 'green' : 'default'">
              {{ record.showInNav ? '显示' : '隐藏' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'sortOrder'">
            <a-tag color="purple">
              {{ record.sortOrder || 0 }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'createTime'">
            <span>{{ record.createdAt }}</span>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space size="middle" class="action-buttons">
              <a-button
                size="small"
                @click="handleEdit(record)"
                class="edit-button"
              >
                <template #icon><EditOutlined /></template>
              </a-button>
              <a-popconfirm
                title="确定要删除这个标签吗？"
                description="删除后该标签下的文章将不受影响，是否继续？"
                @confirm="handleDelete(record.id)"
                ok-text="确定"
                cancel-text="取消"
              >
                <a-button size="small" danger class="delete-button">
                  <template #icon><DeleteOutlined /></template>
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>

      <!-- 空状态展示 -->
      <div v-if="!loading && tags.length === 0" class="empty-state">
        <div class="empty-icon">🏷️</div>
        <p class="empty-text">暂无标签数据</p>
        <p class="empty-description">点击上方"新增标签"按钮开始添加</p>
      </div>
    </a-card>

    <!-- 新增/编辑标签弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      class="tag-modal"
      :transitionName="'fade'"
    >
      <a-form
        :model="tagForm"
        :rules="tagRules"
        ref="tagFormRef"
        layout="vertical"
      >
        <a-form-item name="name" label="标签名称" class="form-item">
          <a-input
            v-model:value="tagForm.name"
            placeholder="请输入标签名称"
            class="form-input"
            allowClear
            @input="handleNameInput"
          />
        </a-form-item>
        <a-form-item name="showInNav" label="显示设置" class="form-item">
          <a-checkbox v-model:checked="tagForm.showInNav">
            显示在导航栏
          </a-checkbox>
        </a-form-item>
        <a-form-item name="sortOrder" label="优先级" class="form-item">
          <a-input-number
            v-model:value="tagForm.sortOrder"
            placeholder="请输入优先级（数字越小越靠前）"
            :min="0"
            :max="999"
            class="form-input"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 标签详情弹窗 -->
    <a-modal
      v-model:open="detailVisible"
      :title="currentTag?.name || '标签详情'"
      @cancel="handleDetailCancel"
      :footer="null"
      class="tag-detail-modal"
    >
      <div v-if="currentTag" class="tag-detail-content">
        <div class="detail-row">
          <span class="detail-label">标签名称：</span>
          <span class="detail-value">{{ currentTag.name }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">文章数量：</span>
          <span class="detail-value">{{ currentTag.count || 0 }} 篇</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">显示在导航：</span>
          <span class="detail-value">
            <a-tag :color="currentTag.showInNav ? 'green' : 'default'">
              {{ currentTag.showInNav ? '显示' : '隐藏' }}
            </a-tag>
          </span>
        </div>
        <div class="detail-row">
          <span class="detail-label">优先级：</span>
          <span class="detail-value">{{ currentTag.sortOrder || 0 }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">创建时间：</span>
          <span class="detail-value">{{ currentTag.createdAt }}</span>
        </div>
        <div class="detail-actions">
          <a-button @click="handleEdit(currentTag)" class="edit-button">
            <template #icon><EditOutlined /></template>
          </a-button>
          <a-button
            danger
            @click="handleDelete(currentTag.id)"
            class="delete-button"
          >
            <template #icon><DeleteOutlined /></template>
          </a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { message, Popconfirm } from "ant-design-vue";
import tagApi from "@/api/tag";

const loading = ref(false);
const tags = ref([]);
const modalVisible = ref(false);
const modalTitle = ref("新增标签");
const currentTagId = ref(null);
const tagFormRef = ref();
const tagForm = reactive({
  name: "",
  showInNav: false,
  sortOrder: 0
});
const detailVisible = ref(false);
const currentTag = ref(null);

const tagRules = {
  name: [
    { required: true, message: "请输入标签名称", trigger: "blur" },
    {
      min: 1,
      max: 15,
      message: "标签名称长度在 1 到 15 个字符",
      trigger: "blur",
    },
    {
      validator: (rule, value, callback) => {
        const isDuplicate = tags.value.some(
          (tag) => tag.id !== currentTagId.value && tag.name === value
        );
        if (isDuplicate) {
          callback(new Error("标签名称已存在"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  sortOrder: [
    { required: true, message: '请输入优先级', trigger: 'blur' },
    { type: 'number', min: 0, max: 999, message: '优先级范围在 0 到 999', trigger: 'blur' }
  ]
};

const columns = [
  {
    title: "标签名称",
    dataIndex: "name",
    key: "name",
    width: 220,
    sorter: (a, b) => a.name.localeCompare(b.name),
  },
  {
    title: "文章数量",
    dataIndex: "count",
    key: "count",
    width: 120,
    sorter: (a, b) => (a.count || 0) - (b.count || 0),
  },
  {
    title: '显示在导航',
    dataIndex: 'showInNav',
    key: 'showInNav',
    width: 120,
    sorter: (a, b) => (a.showInNav ? 1 : 0) - (b.showInNav ? 1 : 0)
  },
  {
    title: '优先级',
    dataIndex: 'sortOrder',
    key: 'sortOrder',
    width: 100,
    sorter: (a, b) => (a.sortOrder || 0) - (b.sortOrder || 0)
  },
  {
    title: "创建时间",
    dataIndex: "createdAt",
    key: "createTime",
    width: 180,
    sorter: (a, b) => new Date(a.createdAt) - new Date(b.createdAt),
  },
  {
    title: "操作",
    key: "action",
    width: 180,
    fixed: "right",
  },
];

// 标签颜色配置
const tagColors = [
  "magenta",
  "red",
  "volcano",
  "orange",
  "gold",
  "lime",
  "green",
  "cyan",
  "blue",
  "geekblue",
  "purple",
  "pink",
];

// 根据标签名生成颜色
const getTagColor = (tagName) => {
  let hash = 0;
  for (let i = 0; i < tagName.length; i++) {
    hash = tagName.charCodeAt(i) + ((hash << 5) - hash);
  }
  return tagColors[Math.abs(hash) % tagColors.length];
};

// 输入标签名时的处理
const handleNameInput = () => {
  // 移除实时验证，避免与表单规则重复
  // 表单规则已经包含了重复检查
};

// 显示标签详情
const showTagDetails = (tag) => {
  currentTag.value = { ...tag };
  detailVisible.value = true;
};

// 关闭详情弹窗
const handleDetailCancel = () => {
  detailVisible.value = false;
  currentTag.value = null;
};

const fetchTags = async () => {
  try {
    loading.value = true;
    const response = await tagApi.getTags();
    if (response.code === 200 && response.data) {
      tags.value = response.data;
    }
  } catch (error) {
    message.error("获取标签列表失败");
  } finally {
    loading.value = false;
  }
};

const showAddModal = () => {
  modalTitle.value = "新增标签";
  currentTagId.value = null;
  tagForm.name = "";
  tagForm.showInNav = false;
  tagForm.sortOrder = 0;
  modalVisible.value = true;
};

const handleEdit = (record) => {
  modalTitle.value = "编辑标签";
  currentTagId.value = record.id;
  tagForm.name = record.name;
  tagForm.showInNav = record.showInNav || false;
  tagForm.sortOrder = record.sortOrder || 0;
  modalVisible.value = true;
  // 如果打开了详情弹窗，则关闭它
  if (detailVisible.value) {
    handleDetailCancel();
  }
};

const handleModalOk = async () => {
  try {
    await tagFormRef.value.validate();

    let response;
    if (currentTagId.value) {
      // 编辑标签
      response = await tagApi.updateTag(currentTagId.value, tagForm);
    } else {
      // 新增标签
      response = await tagApi.addTag(tagForm);
    }

    if (response.code === 200) {
      message.success(currentTagId.value ? "编辑成功" : "新增成功");
      modalVisible.value = false;
      fetchTags();
    }
  } catch (error) {
    message.error(error.message || "操作失败，请重试");
  }
};

const handleModalCancel = () => {
  modalVisible.value = false;
  tagFormRef.value?.resetFields();
};

const handleDelete = async (id) => {
  try {
    const response = await tagApi.deleteTag(id);
    if (response.code === 200) {
      message.success("删除成功");
      fetchTags();
      // 如果打开了详情弹窗，则关闭它
      if (detailVisible.value) {
        handleDetailCancel();
      }
    }
  } catch (error) {
    message.error(error.message || "删除失败");
  }
};

onMounted(() => {
  fetchTags();
});
</script>

<style scoped>
.tag-list-container {
  width: 100%;
  height: 100%;
  padding: 24px;
}

.tag-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 4px;
}

.header-left h2 {
  margin-bottom: 4px;
  color: #262626;
  font-size: 20px;
}

.header-subtitle {
  font-size: 14px;
  color: #999;
  margin: 0;
}

.add-tag-button {
  height: 40px;
  font-size: 14px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.add-tag-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

.tag-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
  transition: all 0.3s ease;
  padding: 24px;
}

.tag-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 标签云样式 */
.tag-cloud {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 24px;
}

.tag-cloud-item {
  position: relative;
  transition: all 0.3s ease;
}

.tag-cloud-item:hover {
  transform: translateY(-2px);
}

.tag-cloud-item:hover .tag-actions {
  opacity: 1;
}

.tag-item {
  font-size: 14px;
  padding: 4px 12px;
  border-radius: 16px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.tag-count {
  margin-left: 6px;
  font-size: 12px;
  opacity: 0.8;
}

.tag-actions {
  position: absolute;
  right: -40px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 10;
}

.tag-action-btn {
  width: 28px;
  height: 28px;
  padding: 0;
  border-radius: 4px;
  background-color: #fff;
  border: 1px solid #d9d9d9;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

.tag-action-btn:hover {
  background-color: #f5f5f5;
  color: #1890ff;
}

/* 表格样式 */
.tag-table {
  border-radius: 8px;
  overflow: hidden;
}

.tag-table .ant-table-thead > tr > th {
  background-color: #fafafa;
  font-weight: 500;
  color: #262626;
  border-bottom: 1px solid #f0f0f0;
}

.tag-table .ant-table-tbody > tr {
  transition: all 0.3s ease;
}

.tag-table .ant-table-tbody > tr:hover > td {
  background-color: #f5f5f5;
}

.count-tag {
  font-size: 12px;
  padding: 0 8px;
  height: 20px;
  border-radius: 4px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.edit-button,
.delete-button {
  height: 28px;
  font-size: 12px;
  padding: 0 12px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.edit-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.delete-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(255, 77, 79, 0.3);
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #666;
}

.empty-description {
  font-size: 14px;
  color: #999;
}

/* 弹窗样式 */
.tag-modal,
.tag-detail-modal {
  border-radius: 8px;
}

.form-item {
  margin-bottom: 16px;
}

.form-input {
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.form-input:focus {
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 标签详情弹窗样式 */
.tag-detail-content {
  padding: 16px 0;
}

.detail-row {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 8px 0;
}

.detail-label {
  width: 100px;
  font-weight: 500;
  color: #666;
}

.detail-value {
  flex: 1;
  color: #262626;
}

.detail-actions {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  gap: 12px;
}

.detail-actions .edit-button,
.detail-actions .delete-button {
  height: 32px;
  padding: 0 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .tag-list-container {
    padding: 16px;
  }

  .tag-list-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }

  .add-tag-button {
    width: 100%;
  }

  .tag-card {
    padding: 16px;
  }

  .tag-cloud {
    gap: 8px;
  }

  .tag-item {
    font-size: 12px;
    padding: 2px 8px;
  }

  .tag-actions {
    display: none;
  }

  .tag-table {
    font-size: 12px;
  }

  .detail-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .detail-label {
    width: 100%;
  }

  .detail-actions {
    flex-direction: column;
  }
}
</style>